// 引入模块
const
  gulp = require('gulp'),
  cleanCss = require("gulp-clean-css"), //压缩css
  htmlmin = require("gulp-htmlmin"), //压缩HTML
  uglify = require("gulp-uglify"), //压缩js
  babel = require("gulp-babel"), //babel转换
  sass = require("gulp-sass"), //sass编译
  connect = require("gulp-connect") //websever
// 定制任务：压缩css
gulp.task("minify-css", function (done) {
  return gulp.src("./src/css/**/*.css") //用两个*号表示的是css下的所有css文件
    .pipe(cleanCss())
    .pipe(gulp.dest("./dist/css"))
  done()
})

// 定制任务：压缩html
gulp.task("minify-html", function (done) {
  return gulp.src("./src/**/*.html")
    .pipe(htmlmin({
      collapseWhitespace: true,
      removeComments: true
    }))
    .pipe(gulp.dest("./dist"))
    .pipe(connect.reload())
})

// 定制任务：压缩js
gulp.task('minify-js', function (done) {
  return gulp.src("./src/js/**/*.js")
    .pipe(babel({
      presets: ["env"]
    }))
    .pipe(uglify())
    .pipe(gulp.dest("./dist/js"))
})

// 定制任务：编译scss,将后缀名为*.scss的文件编译成后缀为css的文件
gulp.task("compile-sass", function (done) {
  return gulp.src("./src/**/*.scss")
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(gulp.dest("./dist/css"))
    .pipe(connect.reload())
})

// 定制任务：复制images、libs目录
gulp.task("copy-images", function (done) {
  return gulp.src("./src/images/**/*.*")
    .pipe(gulp.dest("./dist/images"))
})

gulp.task("copy-libs", function (done) { //json文件类似复制
  return gulp.src("./src/libs/**/*.*")
    .pipe(gulp.dest("./dist/libs"))
})
gulp.task("copy", gulp.series(["copy-images", "copy-libs", done => done()]));


// webserver
gulp.task("start-server", function (done) {
  return connect.server({
    name: 'Dev App',
    root: "dist",
    port: 3000,
    livereload: true
  })
})


// 监视
gulp.task("watch", function (done) {
  gulp.watch("./src/**/*.scss", gulp.series(["compile-sass"]))
  gulp.watch("./src/**/*.html", gulp.series(["minify-html"]))
  done()
})
// 定制默认任务
gulp.task("default", gulp.series("minify-css", "minify-html", 'minify-js', "compile-sass", "copy", "watch", "start-server", done => done()))
// gulp.task("default", ["minify-css", "minify-html"])